package com.sk.sourcecircle.activity.community.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.home.activity.ChatActivity;
import com.sk.sourcecircle.activity.home.activity.PersonDetailsActivity;
import com.sk.sourcecircle.adapter.ChatListAdapter;
import com.sk.sourcecircle.base.BaseFragment;
import com.sk.sourcecircle.callback.MyCallBack;
import com.sk.sourcecircle.dialog.TipDialogFragment;
import com.sk.sourcecircle.entity.MyEMConversation;
import com.sk.sourcecircle.utils.MyUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by sk on 2017/11/23.
 */

public class ChatFragment extends BaseFragment implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemLongClickListener, BaseQuickAdapter.OnItemChildClickListener {
    protected List<MyEMConversation> conversations = new ArrayList<MyEMConversation>();
    @BindView(R.id.data_ryc)
    RecyclerView dataRyc;
    Unbinder unbinder;
    private ChatListAdapter chatListAdapter;

    public static Handler handler;


    @Override
    protected int getContentView() {
        return R.layout.fragment_chat;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        dataRyc.setLayoutManager(new LinearLayoutManager(mContext));
        chatListAdapter = new ChatListAdapter(conversations);
        dataRyc.setAdapter(chatListAdapter);
        View emptyView = getLayoutInflater().inflate(R.layout.empty_view, null);
        chatListAdapter.setEmptyView(emptyView);
        chatListAdapter.setOnItemClickListener(this);
        chatListAdapter.setOnItemChildClickListener(this);
        chatListAdapter.setOnItemLongClickListener(this);
        doRefresh();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                doRefresh();
            }
        };
    }


    private void doRefresh() {
        conversations.clear();
        List<EMConversation> conversationList = loadConversationList();

        Log.v("doRefresh", JSON.toJSONString(conversationList));

        for (EMConversation conversation : conversationList) {
            MyEMConversation myEMConversation = new MyEMConversation();
            myEMConversation.setConversation(conversation);
            conversations.add(myEMConversation);
        }
        chatListAdapter.notifyDataSetChanged();
    }

    protected List<EMConversation> loadConversationList() {
        // get all conversations
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        EMConversation conversation = conversations.get(position).getConversation();
        Intent intent = new Intent(getActivity(), ChatActivity.class);
        String username = conversation.conversationId();
        Log.v("username", username);
        if (conversation.isGroup()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
                // it's group chat
                intent.putExtra("type", 3);
            } else {
                intent.putExtra("type", 2);
            }
            intent.putExtra("toName", (String) conversation.getLastMessage().ext().get("toName"));
            intent.putExtra("toUrl", (String) conversation.getLastMessage().ext().get("toUrl"));
            intent.putExtra("groupName", String.valueOf(conversation.getLastMessage().ext().get("groupName")));
            intent.putExtra("toId", String.valueOf(conversation.getLastMessage().ext().get("toId")));

        } else {
            if (conversation.getLastMessage().getFrom().equals(MyUtils.getUser(mContext).getHx_login())) {
                intent.putExtra("toName", (String) conversation.getLastMessage().ext().get("toName"));
                intent.putExtra("toUrl", (String) conversation.getLastMessage().ext().get("toUrl"));
                intent.putExtra("toId", String.valueOf(conversation.getLastMessage().ext().get("toId")));
            } else {
                intent.putExtra("toName", (String) conversation.getLastMessage().ext().get("nickname"));
                intent.putExtra("toUrl", (String) conversation.getLastMessage().ext().get("head_url"));
                intent.putExtra("toId", String.valueOf(conversation.getLastMessage().ext().get("user_id")));
            }
        }
        // it's single chat
        intent.putExtra("id", username);
        startActivity(intent);
    }


    @Override
    public boolean onItemLongClick(final BaseQuickAdapter adapter, View view, final int position) {
        TipDialogFragment tipDialogFragment = new TipDialogFragment();
        tipDialogFragment.setContent("是否删除该条聊天对话框？");
        tipDialogFragment.setMyCallBack(new MyCallBack() {
            @Override
            public void releaseAlbum() {

            }

            @Override
            public void joinGroup() {

            }

            @Override
            public void takePhoto() {

            }

            @Override
            public void choosePhoto() {

            }

            @Override
            public void sure() {
                EMConversation conversation = conversations.get(position).getConversation();
                String username = conversation.conversationId();
                EMClient.getInstance().chatManager().deleteConversation(username, true);
                conversations.remove(position);
                adapter.notifyItemRemoved(position);
            }

            @Override
            public void cancelOder(String string) {

            }

            @Override
            public void chooseGroup(String id) {

            }

            @Override
            public void cancel() {

            }

            @Override
            public void sendText(String comment) {

            }
        });
        tipDialogFragment.show(getChildFragmentManager(), "delete");
        return false;
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.head_img:
                EMConversation conversation = conversations.get(position).getConversation();
                String id = "";
                if (conversation.getLastMessage().getFrom().equals(MyUtils.getUser(mContext).getHx_login())) {
                    id = String.valueOf(conversation.getLastMessage().ext().get("toId"));
                } else {
                    id = String.valueOf(conversation.getLastMessage().ext().get("user_id"));
                }
                if(id!=null&&id.length()>0){
                    Intent intent = new Intent(mContext, PersonDetailsActivity.class);
                    intent.putExtra("id", Integer.parseInt(id));
                    startActivity(intent);
                }
                break;
        }
    }
}
